<template>
  <div class="horizontal-bar-chart-container" :style="containerStyle">
    <h3 v-if="title" class="chart-title">{{ title }}</h3>
    <div ref="chartRef" class="chart-wrapper"></div>
    <div class="chart-data-info" v-if="chartData.length > 0">
      <div class="data-item" v-for="(item, index) in chartData" :key="index">
        <div class="data-label">{{ item.name }}</div>
      </div>
    </div>
    <div class="data-value-content">
      <div class="data-value" v-for="(item, index) in chartData" :key="index">
        <span class="gender-dot" :class="'dot' + (index + 1)"></span>
        <span style="padding-right: 10px">{{ item.name }}</span>
        <span>{{ item.value }}</span>
        <span class="data-percent">{{ getPercent(item.value) }}%</span>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "HorizontalBarChart",
  props: {
    // 图表数据，格式: [{name: '类别1', value: 100}, ...]
    chartData: {
      type: Array,
      default: () => [],
      required: true,
    },
    // 图表标题
    title: {
      type: String,
      default: "",
    },
    // 柱状图颜色配置
    colors: {
      type: Array,
      default: () => ["#E2EFFE", "#A8CEFC", "#6EADFA", "#348CF8"],
    },
    // 图表高度
    height: {
      type: Number,
      default: 200,
    },
    // 图表位置控制 - 新增属性
    gridLeft: {
      type: String,
      default: "24%",
    },
    gridRight: {
      type: String,
      default: "5%",
    },
    gridTop: {
      type: String,
      default: "10%",
    },
    gridBottom: {
      type: String,
      default: "15%",
    },
    // 容器位置控制 - 新增属性
    position: {
      type: String,
      default: "relative", // relative, absolute, fixed
      validator: (value) => ["relative", "absolute", "fixed"].includes(value),
    },
    left: {
      type: String,
      default: "0%",
    },
    right: {
      type: String,
      default: "10%",
    },
    top: {
      type: String,
      default: "-50",
    },
    bottom: {
      type: String,
      default: "5%",
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  computed: {
    // 计算总数值
    totalValue() {
      return this.chartData.reduce((sum, item) => sum + item.value, 0);
    },
    // 提取标签和数值
    labels() {
      return this.chartData.map((item) => item.name);
    },
    values() {
      return this.chartData.map((item) => item.value);
    },
    // 容器样式 - 新增计算属性
    containerStyle() {
      const style = {
        position: this.position,
      };

      // 添加位置相关样式
      if (this.left) style.left = this.left;
      if (this.right) style.right = this.right;
      if (this.top) style.top = this.top;
      if (this.bottom) style.bottom = this.bottom;

      return style;
    },
  },
  mounted() {
    // 初始化图表
    this.initChart();
    // 监听窗口大小变化，重绘图表
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    // 销毁图表实例，释放资源
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener("resize", this.handleResize);
  },
  watch: {
    // 监听图表数据变化，重新渲染图表
    chartData: {
      handler(newData) {
        if (this.chart && newData && newData.length > 0) {
          this.updateChart();
        }
      },
      deep: true,
    },
    // 监听标题变化，更新图表标题
    title: {
      handler(newTitle) {
        if (this.chart) {
          this.chart.setOption({
            title: {
              text: newTitle,
            },
          });
        }
      },
    },
    // 监听高度变化，更新图表高度
    height: {
      handler(newHeight) {
        if (this.$refs.chartRef) {
          this.$refs.chartRef.style.height = `${newHeight}px`;
        }
        if (this.chart) {
          this.chart.resize();
        }
      },
    },
    // 监听位置属性变化，更新图表位置
    gridLeft: {
      handler() {
        if (this.chart) {
          this.updateChartPosition();
        }
      },
    },
    gridRight: {
      handler() {
        if (this.chart) {
          this.updateChartPosition();
        }
      },
    },
    gridTop: {
      handler() {
        if (this.chart) {
          this.updateChartPosition();
        }
      },
    },
    gridBottom: {
      handler() {
        if (this.chart) {
          this.updateChartPosition();
        }
      },
    },
  },
  methods: {
    // 计算百分比
    getPercent(value) {
      if (!value || this.totalValue === 0) return 0;
      return Math.round((value / this.totalValue) * 100);
    },
    initChart() {
      if (!this.$refs.chartRef) return;

      // 设置图表高度
      this.$refs.chartRef.style.height = `${this.height}px`;

      // 初始化图表实例
      this.chart = echarts.init(this.$refs.chartRef);
      this.updateChart();
    },

    // 更新图表配置
    updateChart() {
      if (!this.chart || !this.chartData || this.chartData.length === 0) return;

      // 设置图表配置项
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: (params) => {
            const data = params[0];
            const percent = this.getPercent(data.value);
            return `${data.name}<br/>${data.value} (${percent}%)`;
          },
        },
        grid: {
          left: this.gridLeft,
          right: this.gridRight,
          bottom: this.gridBottom,
          top: this.gridTop,
          containLabel: true,
        },
        xAxis: {
          type: "value",
          show: false, // 隐藏x轴
          max: Math.max(...this.values) * 1.2, // 设置最大值为数据最大值的1.2倍
        },
        yAxis: {
          type: "category",
          data: this.labels,
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: false, // 隐藏y轴标签，使用自定义的标签
          },
        },
        series: [
          {
            name: this.title || "数据统计",
            type: "bar",
            data: this.values,
            barWidth: "10px",
            itemStyle: {
              color: (params) => {
                // 如果数据中有color属性，则使用数据中的颜色，否则使用默认颜色数组
                return (
                  this.chartData[params.dataIndex].color ||
                  this.colors[params.dataIndex % this.colors.length]
                );
              },
              borderRadius: [10, 10, 10, 10], // 圆角只设置在右侧
            },
            label: {
              show: false, // 不显示默认标签，使用自定义的标签
            },
            animationType: "scale",
            animationEasing: "elasticOut",
            animationDelay: (idx) => {
              return Math.random() * 200;
            },
          },
        ],
      };

      // 设置配置项到图表
      this.chart.setOption(option, true);
    },

    // 单独更新图表位置
    updateChartPosition() {
      if (!this.chart) return;

      this.chart.setOption({
        grid: {
          left: this.gridLeft,
          right: this.gridRight,
          bottom: this.gridBottom,
          top: this.gridTop,
        },
      });
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },

    // 提供外部更新数据的方法
    updateData(newData) {
      // 触发事件，让父组件更新数据，而不是直接修改props
      this.$emit("update-data", newData);
    },
  },
};
</script>

<style scoped>
.horizontal-bar-chart-container {
  position: relative;
  width: 100%;
  min-width: 300px;
  max-width: 800px;
  margin: 0 auto;
  padding: 10px;
  box-sizing: border-box;
}

.chart-title {
  font-size: 16px;
  color: #333;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
}

.chart-wrapper {
  width: 100%;
  position: relative;
}

.chart-data-info {
  position: absolute;
  top: 30px;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}
/* 分别设置四个竹梯的边距样式 */
.data-item:first-child {
  padding-left: 10px;
  margin-top: 4px;
  margin-bottom: 10px;
  /* display: flex;
  justify-content: space-between;
  align-items: center; */
  /* padding: 0 10px; */
  /* height: 25%; */
  box-sizing: border-box;
}
.data-item:nth-child(2) {
  padding-left: 10px;
}
.data-item:nth-child(4) {
  padding-left: 10px;
}
.data-item:nth-child(3) {
  padding-left: 10px;
  margin-top: 10px;
  margin-bottom: 13px;
  /* display: flex;
  justify-content: space-between;
  align-items: center; */
  /* padding: 0 10px; */
  /* height: 25%; */
  box-sizing: border-box;
}

.data-label {
  font-size: 12px;
  color: #333;
  font-weight: 500;
}
.data-value-content {
  margin-top: -20px;
  display: grid;
  gap: 5px;
  grid-template-columns: 1fr 1fr;
}
.dot1 {
  background-color: #348cf8;
}
.dot2 {
  background-color: #6eadfa;
}
.dot3 {
  background-color: #a8cefc;
}
.dot4 {
  background-color: #e2effe;
}
.gender-dot {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}
.data-value {
  /* position: absolute; */
  font-size: 12px;
  /* font-weight: bold; */
  display: flex;
  align-items: center;
}

.data-value span {
  color: #333;
}

.data-percent {
  margin-left: 5px;
  color: #666;
  font-weight: normal;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .horizontal-bar-chart-container {
    min-width: auto;
  }

  .data-label,
  .data-value {
    font-size: 12px;
  }
}
</style>
